package com.wpzf.ndhc.utils;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.HexUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.SM2;
import cn.hutool.crypto.symmetric.SM4;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.shaded.com.google.gson.Gson;
import com.wpzf.common.core.utils.StringUtils;
import com.wpzf.common.core.web.domain.AjaxResult;
import com.wpzf.ndhc.domain.*;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.ui.ModelMap;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.*;

public class GTYUtil {
    private final static String privateKey = "E4F22E79D141717AA63231A9DF53F4062545F17950BCB87B184B0128C6CC494E";
    private final static String publicKey = "04D33B320ED4819E4BC0CBE579EA8C1EC5D23A63922C3A62C7DF46EE800777363B3F97B3E103D47933052F793BA1C55EAB5826B58A886D9FFE2565F3C8EFCCD8B1";
    private final static String gtypublicKey = "04CF7CAE31B5130D1D5D1AC1DC2778D94533868A8D57FC02BBD97B688E07145DAAA96462DC83D9F348261F738D51C049770C43BA53B584917C9E30C6221B737CDD";

    public Map<String, Object> getUploadFilePath(String xzqdm) {
        Map<String, Object> m1 = new HashMap<>();
        //(1)生成适用于SM4算法的随机密钥C sm4Key（128bit）
        byte[] keyC = SecureUtil.generateKey("SM4").getEncoded();
        //String include_xzqdms=parm.get("xzqdms").toString();
        //(2)使用密钥C，采用SM4算法对接口参数进行加密并编译成base64编码
        String data = "{\"code\": \"WPZFNDTB2024_RECV\",\n" +
                "\"regioncode\":\"" + xzqdm.substring(0, 6) + "\"," +
                "\"filenames\":[\"" + xzqdm + ".db\"]}";
        System.out.println("原始参数:" + data);

        byte[] dataByte = data.getBytes(StandardCharsets.UTF_8);
        SM4 sm4 = new SM4(keyC);
        byte[] sm4EncryptDataByte = sm4.encrypt(dataByte);
        String params = Base64.encode(sm4EncryptDataByte);
        System.out.println("参数加密后:" + Base64.encode(sm4EncryptDataByte));

        //(3)使用服务提供方的公钥B，采用SM2加密算法对密钥C进行加密并编码成base64写入Header的x-lc-secret中
        SM2 sm2 = new SM2(null, gtypublicKey);
        sm2.usePlainEncoding();
        byte[] sm2EncryptDataByte = sm2.encrypt(keyC, KeyType.PublicKey);
        String secret = Base64.encode(sm2EncryptDataByte);
        System.out.println("输入secret:" + secret);

        //(4)生成token
        String token = createToken();
        System.out.println("输入token:" + token);

        //(5)发送请求，获取返回值
        String postURL = "https://openapi.landcloud.org.cn/v1/DataExchange/getUploadFilePath";
        try {
            URL url = new URL(postURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("Charset", "utf-8");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8 ");
            conn.setRequestProperty("x-lc-token", token);
            conn.setRequestProperty("x-lc-secret", secret);
            conn.setRequestProperty("x-lc-datacode", "WPZFNDTB2024_RECV");

            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setConnectTimeout(2000);
            conn.setReadTimeout(2000);
            //获取URLConnection对象对应的输出流
            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "utf-8");
            out.write(params);
            out.flush();

            InputStream is = conn.getInputStream();
            int count = 0;
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[4096];
            while ((count = is.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, count);
            }
            byte[] datas = byteArrayOutputStream.toByteArray();
            byteArrayOutputStream.close();
            is.close();
            conn.disconnect();
            String rest = new String(datas, 0, datas.length, "utf-8");
            JSONObject obj = JSONObject.parseObject(rest);

            // 获取响应头
            Map<String, java.util.List<String>> headerFields = conn.getHeaderFields();
            String resecret = headerFields.get("x-lc-secret").get(0);
            System.out.println("输出结果resecret:" + resecret);
            sm2 = new SM2(privateKey, publicKey);
            sm2.usePlainEncoding();
            //SM2 解密SM4密钥
            byte[] decode = sm2.decrypt(resecret, KeyType.PrivateKey);
            //SM4解密内容
            sm4 = new SM4(decode);
            if (obj.get("data") != null) {
                byte[] sm4DataByte = sm4.decrypt(obj.get("data").toString());
                System.out.println("data解密结果:" + new String(sm4DataByte, StandardCharsets.UTF_8));

                String result = new String(sm4DataByte, StandardCharsets.UTF_8);
                JSONArray arraylist = JSONObject.parseArray(result);
                if (arraylist.size() > 0) {
                    for (int i = 0; i < arraylist.size(); i++) {
                        JSONObject jsonObject = arraylist.getJSONObject(i);
                        String writeurl = jsonObject.getString("writeurl");//DB包写入地址
                        String readurl = jsonObject.getString("readurl");//DB包读取地址

                        JSONObject contenttypeObject = JSONObject.parseObject(jsonObject.getString("header"));
                        String contenttype ="";
                        try
                        {
                            contenttype =contenttypeObject.get("content-type").toString();
                        }
                        catch (Exception ex)
                        {
                             contenttype = contenttypeObject.get("Content-Type").toString();
                        }
                        m1.put("code", 200);
                        m1.put("result", result);
                        m1.put("writeurl", writeurl);
                        m1.put("readurl", readurl);
                        m1.put("contenttype", contenttype);
                        m1.put("message", "获取地址成功");
                    }
                    return m1;
                } else {
                    m1.put("code", 500);
                    m1.put("message", "获取上传地址失败");
                    return m1;
                }
            } else {
                m1.put("code", 500);
                m1.put("message", "获取上传地址失败");
                return m1;
            }
        } catch (Exception ex) {
            m1.put("code", 500);
            m1.put("message", ex.toString());
            return m1;
        }
    }


    public static String createToken() {
        String privateKey = "E4F22E79D141717AA63231A9DF53F4062545F17950BCB87B184B0128C6CC494E";
        String publicKey = "04D33B320ED4819E4BC0CBE579EA8C1EC5D23A63922C3A62C7DF46EE800777363B3F97B3E103D47933052F793BA1C55EAB5826B58A886D9FFE2565F3C8EFCCD8B1";

        //SM2
        SM2 sm2 = new SM2(privateKey, publicKey);
        sm2.usePlainEncoding();
        //SM2 token生成
        String certCode = "API32_YXK33YEGLXMUVMOYEQ43JWE4EU";
        long timestamp = System.currentTimeMillis();
        //拼接待签名数据
        String needSignData = certCode + timestamp;
        byte[] needSignDataByte = needSignData.getBytes(StandardCharsets.UTF_8);
        //签名
        byte[] signData = sm2.sign(needSignDataByte);
        //签名
        String signDataHex = HexUtil.encodeHexStr(signData);

        String signDataBase64 = cn.hutool.core.codec.Base64.encode(signData);
        //生成token
        String token = certCode + "." + timestamp + "." + signDataBase64;

        //SM2 token验证
        boolean rst1 = sm2.verify(needSignDataByte, signData);
        boolean rst2 = sm2.verify(needSignDataByte, HexUtil.decodeHex(signDataHex));
        boolean rst3 = sm2.verify(needSignDataByte, Base64.decode(signDataBase64));
        System.out.println("verify result:" + rst3);
        return token;
    }

    public boolean uploadObject(String writeurl, String objectLocalPath, String contentType) throws MalformedURLException {
        URL presignedUrl = new URL(writeurl);
        BufferedOutputStream bufferedOutputStream = null;
        BufferedInputStream bufferedInputStream = null;
        try {
            HttpURLConnection httpURLConnection =
                    (HttpURLConnection) presignedUrl.openConnection();
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setRequestProperty("Content-Type", contentType);
            httpURLConnection.setRequestMethod("PUT");
            bufferedOutputStream = new
                    BufferedOutputStream(httpURLConnection.getOutputStream());
            bufferedInputStream = new
                    BufferedInputStream(new FileInputStream(new File(objectLocalPath)));


            byte[] buffer = new byte[1024];
            int length = bufferedInputStream.read(buffer);
            while (length > 0) {
                bufferedOutputStream.write(buffer);
                length = bufferedInputStream.read(buffer);
            }


            bufferedOutputStream.flush();
            bufferedOutputStream.close();
            if (httpURLConnection.getResponseCode() == 200) {
                System.out.println(httpURLConnection.getResponseCode());
                System.out.println(httpURLConnection.getResponseMessage());
                return true;
            } else {
                return false;
            }

        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            if (bufferedOutputStream != null) {
                try {
                    bufferedOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedInputStream != null) {
                try {
                    bufferedInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    public Map<String, Object> pushDataPackage(String data) {
        Map<String, Object> m2 = new HashMap<>();
        //(1)生成适用于SM4算法的随机密钥C sm4Key（128bit）
        byte[] keyC = SecureUtil.generateKey("SM4").getEncoded();
        //(2)使用密钥C，采用SM4算法对接口参数进行加密并编译成base64编码
        System.out.println("原始参数:" + data);

        byte[] dataByte = data.getBytes(StandardCharsets.UTF_8);

        SM4 sm4 = new SM4(keyC);
        byte[] sm4EncryptDataByte = sm4.encrypt(dataByte);
        String params = Base64.encode(sm4EncryptDataByte);
        System.out.println("参数加密后:" + Base64.encode(sm4EncryptDataByte));


        //(3)使用服务提供方的公钥B，采用SM2加密算法对密钥C进行加密并编码成base64写入Header的x-lc-secret中
        SM2 sm2 = new SM2(null, gtypublicKey);
        sm2.usePlainEncoding();
        byte[] sm2EncryptDataByte = sm2.encrypt(keyC, KeyType.PublicKey);
        String secret = Base64.encode(sm2EncryptDataByte);
        System.out.println("输入secret:" + secret);

        //(4)生成token
        String token = createToken();
        System.out.println("输入token:" + token);

        //(5)发送请求，获取返回值
        String postURL = "https://openapi.landcloud.org.cn/v1/DataExchange/pushDataPackage";
        try {
            URL url = new URL(postURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("Charset", "utf-8");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8 ");
            conn.setRequestProperty("x-lc-token", token);
            conn.setRequestProperty("x-lc-secret", secret);
            conn.setRequestProperty("x-lc-datacode", "WPZFNDTB2024_RECV");

            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setConnectTimeout(2000);
            conn.setReadTimeout(2000);
            //获取URLConnection对象对应的输出流
            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "utf-8");
            out.write(params);
            out.flush();

            InputStream is = conn.getInputStream();
            int count = 0;
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[4096];
            while ((count = is.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, count);
            }
            byte[] datas = byteArrayOutputStream.toByteArray();
            byteArrayOutputStream.close();
            is.close();
            conn.disconnect();
            String rest = new String(datas, 0, datas.length, "utf-8");
            JSONObject obj = JSONObject.parseObject(rest);

            // 获取响应头
            Map<String, java.util.List<String>> headerFields = conn.getHeaderFields();
            //(6)从返回头获取
            String resecret = headerFields.get("x-lc-secret").get(0);
            System.out.println("输出结果resecret:" + resecret);


            sm2 = new SM2(privateKey, publicKey);
            sm2.usePlainEncoding();
            //SM2 解密SM4密钥
            byte[] decode = sm2.decrypt(resecret, KeyType.PrivateKey);
            //SM4解密内容
            sm4 = new SM4(decode);
            if (("200").equals(obj.get("code").toString())) {
                byte[] sm4DataByte = sm4.decrypt(obj.get("data").toString());
                System.out.println("jobid:" + new String(sm4DataByte, StandardCharsets.UTF_8));
                m2.put("code", 200);
                m2.put("rest", rest);
                m2.put("x-lc-secret", resecret);
                m2.put("message", new String(sm4DataByte, StandardCharsets.UTF_8));
                return m2;
            } else {
                m2.put("code", 500);
                m2.put("rest", rest);
                m2.put("x-lc-secret", resecret);
                m2.put("message", obj.get("message").toString());
                return m2;
            }
        } catch (Exception ex) {
            m2.put("code", 500);
            m2.put("message", ex.toString());
            return m2;
        }
    }

    public Map<String, Object> getMultipartUploadPath(String xzqdm, long filesize, String filename) {
        Map<String, Object> m1 = new HashMap<>();
        //(1)生成适用于SM4算法的随机密钥C sm4Key（128bit）
        byte[] keyC = SecureUtil.generateKey("SM4").getEncoded();
        //String include_xzqdms=parm.get("xzqdms").toString();
        //(2)使用密钥C，采用SM4算法对接口参数进行加密并编译成base64编码
        String data = "{\"code\": \"WPZFNDTB2024_RECV\",\n" +
                "\"regioncode\":\"" + xzqdm + "\"," +
                "\"filesize\":" + filesize + "," +
                "\"filename\":\"" + xzqdm + ".db\"}";
        System.out.println("原始参数:" + data);

        byte[] dataByte = data.getBytes(StandardCharsets.UTF_8);
        SM4 sm4 = new SM4(keyC);
        byte[] sm4EncryptDataByte = sm4.encrypt(dataByte);
        String params = Base64.encode(sm4EncryptDataByte);
        System.out.println("参数加密后:" + Base64.encode(sm4EncryptDataByte));

        //(3)使用服务提供方的公钥B，采用SM2加密算法对密钥C进行加密并编码成base64写入Header的x-lc-secret中
        SM2 sm2 = new SM2(null, gtypublicKey);
        sm2.usePlainEncoding();
        byte[] sm2EncryptDataByte = sm2.encrypt(keyC, KeyType.PublicKey);
        String secret = Base64.encode(sm2EncryptDataByte);
        System.out.println("输入secret:" + secret);

        //(4)生成token
        String token = createToken();
        System.out.println("输入token:" + token);

        //(5)发送请求，获取返回值
        String postURL = "https://openapi.landcloud.org.cn/v1/DataExchange/getMultipartUploadPath";
        try {
            URL url = new URL(postURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("Charset", "utf-8");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8 ");
            conn.setRequestProperty("x-lc-token", token);
            conn.setRequestProperty("x-lc-secret", secret);
            conn.setRequestProperty("x-lc-datacode", "WPZFNDTB2024_RECV");

            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setConnectTimeout(2000);
            conn.setReadTimeout(2000);
            //获取URLConnection对象对应的输出流
            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "utf-8");
            out.write(params);
            out.flush();

            InputStream is = conn.getInputStream();
            int count = 0;
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[4096];
            while ((count = is.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, count);
            }
            byte[] datas = byteArrayOutputStream.toByteArray();
            byteArrayOutputStream.close();
            is.close();
            conn.disconnect();
            String rest = new String(datas, 0, datas.length, "utf-8");
            JSONObject obj = JSONObject.parseObject(rest);

            // 获取响应头
            Map<String, java.util.List<String>> headerFields = conn.getHeaderFields();
            String resecret = headerFields.get("x-lc-secret").get(0);
            System.out.println("输出结果resecret:" + resecret);
            sm2 = new SM2(privateKey, publicKey);
            sm2.usePlainEncoding();
            //SM2 解密SM4密钥
            byte[] decode = sm2.decrypt(resecret, KeyType.PrivateKey);
            //SM4解密内容
            sm4 = new SM4(decode);
            if (obj.get("code").equals(200)) {
                if (obj.get("data") != null) {
                    byte[] sm4DataByte = sm4.decrypt(obj.get("data").toString());
                    System.out.println("data解密结果:" + new String(sm4DataByte, StandardCharsets.UTF_8));

                    String result = new String(sm4DataByte, StandardCharsets.UTF_8);
                    m1.put("code", 200);
                    m1.put("data", result);
                    m1.put("message", "获取地址成功");
                    return m1;
                } else {
                    m1.put("code", 500);
                    m1.put("message", "获取上传地址失败");
                    return m1;
                }
            } else {
                m1.put("code", 500);
                m1.put("message", obj.get("message").toString());
                return m1;
            }
        } catch (Exception ex) {
            m1.put("code", 500);
            m1.put("message", ex.toString());
            return m1;
        }
    }


    public Map<String, Object> CompleteFlieUpload(String taskid, String objkey, List<PartUploadDTO> parttags) {
        Map<String, Object> m1 = new HashMap<>();
        //(1)生成适用于SM4算法的随机密钥C sm4Key（128bit）
        byte[] keyC = SecureUtil.generateKey("SM4").getEncoded();
        String tags = "";
        for (int i = 0; i < parttags.size(); i++) {
            PartUploadDTO model = parttags.get(i);
            tags += "{\"partnumber\":" + model.getPartnumber() + "," +
                    "\"etag\":\"\\\"" + model.getEtag() + "\\\"\"},";
            System.out.println(tags);
        }
        tags = tags.substring(0, tags.length() - 1);

        //String include_xzqdms=parm.get("xzqdms").toString();
        //(2)使用密钥C，采用SM4算法对接口参数进行加密并编译成base64编码
        String data = "{\"taskid\":\"" + taskid + "\"," +
                "\"objkey\":" + objkey + "," +
                "\"parttags\":[" + tags + "]}";
        System.out.println("原始参数:" + data);

        byte[] dataByte = data.getBytes(StandardCharsets.UTF_8);
        SM4 sm4 = new SM4(keyC);
        byte[] sm4EncryptDataByte = sm4.encrypt(dataByte);
        String params = Base64.encode(sm4EncryptDataByte);
        System.out.println("参数加密后:" + Base64.encode(sm4EncryptDataByte));

        //(3)使用服务提供方的公钥B，采用SM2加密算法对密钥C进行加密并编码成base64写入Header的x-lc-secret中
        SM2 sm2 = new SM2(null, gtypublicKey);
        sm2.usePlainEncoding();
        byte[] sm2EncryptDataByte = sm2.encrypt(keyC, KeyType.PublicKey);
        String secret = Base64.encode(sm2EncryptDataByte);
        System.out.println("输入secret:" + secret);

        //(4)生成token
        String token = createToken();
        System.out.println("输入token:" + token);

        //(5)发送请求，获取返回值
        String postURL = "https://openapi.landcloud.org.cn/v1/DataExchange/CompleteFlieUpload";
        try {
            URL url = new URL(postURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("Charset", "utf-8");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8 ");
            conn.setRequestProperty("x-lc-token", token);
            conn.setRequestProperty("x-lc-secret", secret);
            conn.setRequestProperty("x-lc-datacode", "WPZFNDTB2024_RECV");

            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setConnectTimeout(2000);
            conn.setReadTimeout(2000);
            //获取URLConnection对象对应的输出流
            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "utf-8");
            out.write(params);
            out.flush();

            InputStream is = conn.getInputStream();
            int count = 0;
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[4096];
            while ((count = is.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, count);
            }
            byte[] datas = byteArrayOutputStream.toByteArray();
            byteArrayOutputStream.close();
            is.close();
            conn.disconnect();
            String rest = new String(datas, 0, datas.length, "utf-8");
            JSONObject obj = JSONObject.parseObject(rest);

            // 获取响应头
            Map<String, java.util.List<String>> headerFields = conn.getHeaderFields();
            String resecret = headerFields.get("x-lc-secret").get(0);
            System.out.println("输出结果resecret:" + resecret);
            sm2 = new SM2(privateKey, publicKey);
            sm2.usePlainEncoding();
            //SM2 解密SM4密钥
            byte[] decode = sm2.decrypt(resecret, KeyType.PrivateKey);
            //SM4解密内容
            sm4 = new SM4(decode);
            if (obj.get("code").equals(200)) {
                if (obj.get("data") != null) {
                    byte[] sm4DataByte = sm4.decrypt(obj.get("data").toString());
                    System.out.println("data解密结果:" + new String(sm4DataByte, StandardCharsets.UTF_8));

                    String result = new String(sm4DataByte, StandardCharsets.UTF_8);
                    m1.put("code", 200);
                    m1.put("data", result);
                    m1.put("message", "返回成功");
                    return m1;
                } else {
                    m1.put("code", 500);
                    m1.put("message", "返回失败");
                    return m1;
                }
            } else {
                m1.put("code", 500);
                m1.put("message", obj.get("message").toString());
                return m1;
            }
        } catch (Exception ex) {
            m1.put("code", 500);
            m1.put("message", ex.toString());
            return m1;
        }
    }

    public static Map<String, Object> queryDataPackageState(String jobid) {
        Map<String, Object> map = new HashMap<>();

        //x-lc-token
        String token = createToken();

        //x-lc-secret
        byte[] keyC = SecureUtil.generateKey("SM4").getEncoded();
        SM2 sm2 = new SM2(null, gtypublicKey);
        sm2.usePlainEncoding();
        byte[] sm2EncryptDataByte = sm2.encrypt(keyC, KeyType.PublicKey);
        String secret = Base64.encode(sm2EncryptDataByte);

        String postURL = "https://openapi.landcloud.org.cn/v1/DataExchange/queryDataPackageState/" + jobid;
        try {
            URL url = new URL(postURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("Charset", "utf-8");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8 ");
            conn.setRequestProperty("x-lc-token", token);
            conn.setRequestProperty("x-lc-secret", secret);
            conn.setRequestProperty("x-lc-datacode", "WPZFNDTB2024_RECV");

            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setConnectTimeout(2000);
            conn.setReadTimeout(2000);
            //获取URLConnection对象对应的输出流
//            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "utf-8");
//            out.write(params);
//            out.flush();

            InputStream is = conn.getInputStream();
            int count = 0;
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[4096];
            while ((count = is.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, count);
            }
            byte[] datas = byteArrayOutputStream.toByteArray();
            byteArrayOutputStream.close();
            is.close();
            conn.disconnect();
            String rest = new String(datas, 0, datas.length, "utf-8");
            JSONObject obj = JSONObject.parseObject(rest);

            // 获取响应头
            Map<String, java.util.List<String>> headerFields = conn.getHeaderFields();
            String resecret = headerFields.get("x-lc-secret").get(0);
            System.out.println("输出结果resecret:" + resecret);
            sm2 = new SM2(privateKey, publicKey);
            sm2.usePlainEncoding();
            //SM2 解密SM4密钥
            byte[] decode = sm2.decrypt(resecret, KeyType.PrivateKey);
            //SM4解密内容
            SM4 sm4 = new SM4(keyC);
            sm4 = new SM4(decode);

            map.put("code,", obj.get("code"));
            map.put("message,", obj.get("message"));
            map.put("traceid,", obj.get("traceid"));

            if (obj.get("data") != null) {
                byte[] sm4DataByte = sm4.decrypt(obj.get("data").toString());
                System.out.println("data解密结果:" + new String(sm4DataByte, StandardCharsets.UTF_8));
                String result = new String(sm4DataByte, StandardCharsets.UTF_8);
                Gson gson = new Gson();
                // 将 JSON 字符串转换为 Map
                Map<String, Object> dataMap = gson.fromJson(result, Map.class);
                map.put("data", dataMap);
            }
            return map;
        } catch (Exception ex) {
            map.put("code", 500);
            map.put("message", ex.toString());
            return map;
        }
    }


    //获取国土云token
    public static String getGTYToken() {
        try {
            String postURL = "";
            String data = "";
            {
                postURL = "https://jg.landcloud.org.cn:8553/webapi/token";
                data = "client_id=web&client_secret=e46232c20609435eba54b7576de935dd&grant_type=password&username=a53e0c14ee900728f36bba014d975982&password=b30c775c48e9ba92ade95e427a5242b0";
            }
            URL url = new URL(postURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");

            conn.setDoOutput(true);
            conn.setDoInput(true);
            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "utf-8");

            out.write(data);
            //缓冲数据
            out.flush();
            //获取URLConnection对象对应的输入流
            InputStream is = conn.getInputStream();
            int count = 0;
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[4096];
            while ((count = is.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, count);
            }
            byte[] datas = byteArrayOutputStream.toByteArray();
            byteArrayOutputStream.close();
            //关闭流
            is.close();
            conn.disconnect();
            return new String(datas, 0, datas.length, "utf-8");
        } catch (Exception ex) {
            return "获取国土云token,错误原因:" + ex.getMessage();
        }
    }

    public static String getNDDxxxbsj2024(String str, String ywmb, String xzqdm, String xmbh) {
        String rest = "";
        try {
            String postURL = "";
            String token = "";
            String token_type = "";
            Map mapType = JSON.parseObject(str, Map.class);
            {
                for (Object obj : mapType.keySet()) {

                    if ((obj + "").equals("access_token")) {
                        token = mapType.get("access_token") + "";
                        token_type = mapType.get("token_type") + "";
                    }
                }
                System.out.println(token);
                //接口地址
                postURL = "https://dc2.landcloud.org.cn:9443/webapi/api/open/GetWPZFTBInfo";
            }
            URL url = new URL(postURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            String encoding = com.wpzf.common.core.utils.sign.Base64.encode(str.getBytes());
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("Charset", "utf-8");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8 ");
            conn.setRequestProperty("Authorization", token_type + " " + token);
            //  conn.setRequestProperty("token", token);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setConnectTimeout(20000);
            conn.setReadTimeout(20000);

            String data = "{\"xzqdm\":\"" + xzqdm + "\",\"ywmb\":\"" + ywmb + "\",\"xmbh\":[\"" + xmbh + "\"]}";
            System.out.println("---------获取地块列表参数------" + data);

            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "utf-8");
            if (StringUtils.isNotBlank(xzqdm)) {
                out.write(data);
                out.flush();
                InputStream is = conn.getInputStream();
                int count = 0;
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                byte[] buffer = new byte[4096];
                while ((count = is.read(buffer)) != -1) {
                    byteArrayOutputStream.write(buffer, 0, count);
                }
                byte[] datas = byteArrayOutputStream.toByteArray();

                byteArrayOutputStream.close();
                is.close();
                conn.disconnect();
                rest = new String(datas, 0, datas.length, "utf-8");
                JSONObject obj = JSONObject.parseObject(rest);
                if (obj.get("data") == null) {
                    rest = data + "获取地块信息为null";
                    return rest;
                }
            }
        } catch (Exception e) {
            rest = "网络异常，请稍后重试！";
            return e.getMessage();
        }
        return rest;
    }

    public static String getDkInfo(String xzqdm,String jcbh)
    {
        String rest = "";
       String str= getGTYToken();
        try {
            String postURL = "";
            String token = "";
            String token_type = "";
            Map mapType = JSON.parseObject(str, Map.class);
            {
                for (Object obj : mapType.keySet()) {

                    if ((obj + "").equals("access_token")) {
                        token = mapType.get("access_token") + "";
                        token_type = mapType.get("token_type") + "";
                    }
                }
                System.out.println(token);
                //接口地址
                postURL = "https://dc2.landcloud.org.cn:9443/webapi/wpzfservice/wpzfndtb2024/dkinfoList";
            }
            URL url = new URL(postURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            String encoding = com.wpzf.common.core.utils.sign.Base64.encode(str.getBytes());
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("Charset", "utf-8");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8 ");
            conn.setRequestProperty("Authorization", token_type + " " + token);
            //  conn.setRequestProperty("token", token);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setConnectTimeout(20000);
            conn.setReadTimeout(20000);

            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "utf-8");
            if (StringUtils.isNotBlank(xzqdm)) {
                String data = "{\"xzqdm\":\"" + xzqdm + "\",\"jcbh\":\"" + jcbh + "\"}";
                System.out.println("---------获取地块列表参数------" + data);
                out.write(data);
                out.flush();
                InputStream is = conn.getInputStream();
                int count = 0;
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                byte[] buffer = new byte[4096];
                while ((count = is.read(buffer)) != -1) {
                    byteArrayOutputStream.write(buffer, 0, count);
                }
                byte[] datas = byteArrayOutputStream.toByteArray();

                byteArrayOutputStream.close();
                is.close();
                conn.disconnect();
                rest = new String(datas, 0, datas.length, "utf-8");
                return rest;
            }
        } catch (Exception e) {
            rest = "网络异常，请稍后重试！";
            return e.getMessage();
        }
        return  "";
    }

}
